/*
 * @Description: Table Hooks
 * @Date: 2022-12-28 21:10:53
 * @Author: lizhiqiang
 */
import { useEffect, useState } from "react";
import type { PaginationProps } from 'antd';

export default function useTableData(Func: any, searchForm: any, otherParams?: object, formKey?: string) {
    const [isLoading, setIsLoading] = useState(false);
    const showTotal: PaginationProps['showTotal'] = total => `共 ${total} 条`;
    const [pageInfo, setPageInfo] = useState({
        limit: 10,
        page: 1,
        total: 0,
        showTotal: showTotal
    });
    const [searchParams, setSearchParams] = useState<any>({});
    const [dataSource, setDataSource] = useState([]);
    const defaultFormat = (params: any) => params;
    const onChangeTable = (formatParams = defaultFormat) => {
        const params = searchForm?.getFieldsValue()
        setSearchParams({
            ...searchParams,
            ...otherParams,
            ...formatParams(params)
        })
        setPageInfo({
            ...pageInfo,
            page: 1
        })
    }
    const getTableData = async () => {
        setIsLoading(true);
        const { code, data } =  formKey ? await Func(formKey, {
            ...pageInfo,
            ...searchParams,
            ...otherParams
        }) : await Func({
            ...pageInfo,
            ...searchParams,
            ...otherParams
        })
        if (code === 200) {
            const totals = data.totalCount || data.total;
            const showTotal: PaginationProps['showTotal'] = total => `Total ${total} items`;
            setDataSource((data.list || data.records) ?? [])
            setPageInfo({
                ...pageInfo,
                total: totals,
            })
            setIsLoading(false);
        } else {
            setIsLoading(false);
        }
    }
    useEffect(() => {
        getTableData()
    }, [pageInfo.limit, pageInfo.page, searchParams]);
    return {
        isLoading,
        searchParams,
        setSearchParams,
        dataSource,
        pageInfo,
        setPageInfo,
        getTableData,
        onChangeTable
    }
}